<?php

class Cities extends Controller{

	function cities(){
		parent::Controller();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->model('cities_model');
    	$this->load->library('session');
	}
  
 
  
	function list_cities()
  {
    $user_ses = $this->session->userdata('userlogindetails');
 
    if($user_ses['user_id'] && $user_ses['user_group']==1)
    {
    
      $this->load->helper('flexigrid');
      $this->load->model('states_model');
      $states = $this->states_model->disp_states();
      $displayform = '';
      $displayform .='<div id=dashboard ><span>Manage City</span> <a href='.base_url().'/idea_home/admin_dashboard ><img align=right src="'.base_url().'images/home.png" alt="home" /></a><img align=right src="'.base_url().'images/back.png" alt="back" id=back ONCLICK="history.go(-1)" /></div>';
      $displayform .= '<span style="float:left;">Welcome '.$user_ses['user_name'].'</span><div id=logout><span id="add_city_in_bulk" style="cursor:pointer;color:blue;" >[Add city in bulk]</span>&nbsp;<span id="create-city" style="cursor:pointer;color:blue;" >[Add New City]</span>&nbsp;<a href="'.base_url().'idea_home/logout">Logout</a></div>';
      $displayform .='<br/>';
      
      //MODEL FORM STARTS HERE....
    $displayform .= '<div id="dialog-form" title="New City Form">';
    $displayform .= '<p class="validateTips">Please fill all the details.</p>';
    $displayform .= '<form><fieldset>';
    $displayform .= '<label for="country">Country:</label>';
    $displayform .= '<input type="text" name="country" id="country_name" value="India" class="text ui-widget-content ui-corner-all" disabled=disabled />';
    $displayform .= '<br/>';   
    $displayform .= '<label for="state">State:</label>';
    $displayform .= '<select name="state" id="state_name" class="text ui-widget-content" style="width:245px;">';
    $displayform .= '<option value="">-Please select state name-</option>';
      foreach($states->result_array() as $row)
      {
        $displayform .= '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
      }
    $displayform .= '</select>';
    
    //$displayform .= '<input type="text" name="country" value="India" class="text ui-widget-content ui-corner-all" disabled=disabled />';
    
    $displayform .= '<label for="name">City:</label>';
    $displayform .= '<input type="text" name="city_name" id="city_name" class="text ui-widget-content ui-corner-all" />';
    
    
    $displayform .= '</fieldset></form></div>';
      
      //MODEL FORM ENDS HERE....
      
      
      
      $displayform .= '<div id="duplicate_city"></div>';
      $displayform .= '<table>';
      $displayform .= '<tr><td align=left>State:</td>';
      $displayform .= '<td align=left><select name=state id=state class=required >';
      $displayform .= '<option value=" ">-Please Select State-</option>';
      
      foreach($states->result_array() as $row)
      {
        $displayform .= '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
      }
      $displayform .= '</select></td></tr></table>';
      $displayform .= '<div id=city_list>';
      $displayform .= '<table id="flex1" style="display:none" border=0 align=left ></table>';
      $displayform .= '</div>';
      $displayform .= '<br/>';
    
    $colModel['city_id'] = array('Sl No',60,TRUE,'center',0);
    $colModel['city_name'] = array('City Name',160,TRUE,'left',2);
    
    $gridParams = array(
      'width' => '800',
      'height' => 400,
      'rp' => 15,
      'rpOptions' => '[10,20,30,40,50,60]',
      'pagestat' => 'Displaying:{from} to {to} of {total} items.',
      'blockOpacity' => 0.5,
      'title' => 'List of Cities in Karnataka',
      'showTableToggleBtn' => true
    );
    
    $grid_js = build_grid_js('flex1',site_url("/ajax/city_list/12"),$colModel,'city_id','asc',$gridParams);
    
    $data['js_grid'] = $grid_js;
    //model css comes here..
     $this->template->add_css('
   //     body { font-size: 90%; }
    .label, #country, #state_name,#city_name { display:block; }
   // #state_name.text, #country.text { margin-bottom:12px; width:95%; padding: .4em; }
    fieldset { padding:0; border:0; margin-top:25px; }
    h1 { font-size: 1.2em; margin: .6em 0; }
   
    .ui-dialog .ui-state-error { padding: .3em; }
    .validateTips { border: 1px solid transparent; padding: 0.3em; }
        
    ','embed');
    
    
    //model css ends here....
    //model form jquery starts here...
     $this->template->add_js('js/ui/jquery.ui.position.js');
    $this->template->add_js('js/ui/jquery.ui.mouse.js');
    $this->template->add_js('js/ui/jquery.ui.draggable.js');
    $this->template->add_js('js/ui/jquery.ui.resizable.js');
    $this->template->add_js('js/ui/jquery.ui.dialog.js');
    $this->template->add_js('js/ui/jquery.effects.core.js');
    $this->template->add_js('
     $(function() {
   
    $( "#dialog:ui-dialog" ).dialog( "destroy" );
    
    var city = $( "#city_name" ),
    state = $("#state_name"),
      allFields = $( [] ).add( city ).add( state ),
      tips = $( ".validateTips" );

    function updateTips( t ) {
      tips
        .text( t )
        .addClass( "ui-state-highlight" );
      setTimeout(function() {
        tips.removeClass( "ui-state-highlight", 1500 );
      }, 500 );
    }

    function checkLength( o, n, min, max ) {
      if(o.val()== "")
      {
         o.addClass( "ui-state-error" );
        updateTips( "All the fields required!!" );
        return false;
      }
      
      if ( o.val().length > max || o.val().length < min ) {
        o.addClass( "ui-state-error" );
        updateTips( "Length of " + n + " must be between " +
          min + " and " + max + "." );
        return false;
      } else {
        return true;
      }
    }

    function checkRegexp( o, regexp, n ) {
      if ( !( regexp.test( o.val() ) ) ) {
        o.addClass( "ui-state-error" );
        updateTips( n );
        return false;
      } else {
        return true;
      }
    }
    
    $( "#dialog-form" ).dialog({
      autoOpen: false,
      position:[600,10],
      height: 400,
      width: 350,
      modal: true,
      buttons: {
        "Save": function() {
          var bValid = true;
          allFields.removeClass( "ui-state-error" );

          bValid = bValid && checkLength( city, "City Name", 3, 50 );
          bValid = bValid && checkLength( state, "State Name", 1, 10 );
          bValid = bValid && checkRegexp( city, /^[a-z]([a-z ])+$/i, "City Name may consist of a-z, begin with a letter." );
      
          if ( bValid ) {
              
               $.ajax({
                type: "GET",
                url: "/cities/ajax_addnew_cities/"+ city.val()+"/"+state.val(),
          
                dataType: "text/html",
                success: function(html){       $("#duplicate_city").html(html);     }
          
                  });
                      
            $( this ).dialog( "close" );
          }
        },
        Cancel: function() {
          $( this ).dialog( "close" );
        }
      },
      close: function() {
        allFields.val( "" ).removeClass( "ui-state-error" );
      }
    });

    $( "#create-city" )
     
      .click(function() {
        $( "#dialog-form" ).dialog( "open" );
      });
  });
     
	 $(document).ready(function(){
	 	$("#add_city_in_bulk").click(function(){
	 		window.location = "'.base_url().'cities/add_cities_in_bulk"
			
	 	});
	 });

    ','embed');
    
    //model form jquery ends here....
    
    
    
    $data = array('formdisplay'=>$displayform,'js_grid'=>$grid_js );  
    $this->template->add_css('css/flexigrid/flexigrid.css');
    $this->template->add_js('js/flexigride/flexigrid.pack.js');
    $this->template->add_js(' 
      $(document).ready(function(){
      $("#state").change(function(){
        var src = $(this).val();
        
        if(src == " ")
        {
          alert(" please select a state !!");
          return false;
        }
        else
        {
            $.ajax({
          type: "POST",
          url: "/cities/display_cities/"+ src,
    
          dataType: "text/html",
          success: function(html){       $("#city_list").html(html);     }
                      
        });
        }
              
      });
      
      
      });
      ','embed');
    //ends here....
    $this->template->write_view('header','header', $data, True);
    $this->template->write_view('content', 'other_general');
    $this->template->render();
    }
    else
  {
    echo "Forbidden to access!!";
  }
    
  }
//to add cities in bulk through excel sheet....
	function add_cities_in_bulk()
	{
		$user_ses = $this->session->userdata('userlogindetails');
 
		 if($user_ses['user_id'] && $user_ses['user_group']==1)
		 {
		 	$this->load->model('states_model');
      		$states = $this->states_model->disp_states();
			
    		$displayform ='';
			$displayform .='<div id=dashboard ><span>Upload Cities</span> <a href='.base_url().'/idea_home/admin_dashboard ><img align=right src="'.base_url().'images/home.png" alt="home" /></a><img align=right src="'.base_url().'images/back.png" id="back"" alt="back" ONCLICK="history.go(-1)" /></div>';
			$displayform .= '<span style="float:left;">Welcome '.$user_ses['user_name'].'</span><div id=logout><a href="'.base_url().'idea_home/logout">Logout</a></div>';
			$displayform .= '<div id=upload>';
			$attr = array('class'=>'add_outward','id'=>'add_upload');
			$displayform .= form_open_multipart('cities/save_bulk_cities',$attr);
			$displayform .= '<fieldset id="upload_caf" style="width:40%;">';
	    	$displayform .= ' <legend style="color:black;">Upload File</legend>';
	    	$displayform .= '<center><table cellspacing="20px" >';
			$displayform .= '<tr>';
			$displayform .= '<td>';
			$displayform .= 'state:';
			$displayform .= '</td>';
			$displayform .= '<td>';
			 $displayform .= '<select name="state" id="state_name" class="required" style="width:245px;">';
		    $displayform .= '<option value="">-Please select state name-</option>';
		      foreach($states->result_array() as $row)
		      {
		        $displayform .= '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
		      }
		    $displayform .= '</select>';
		    $displayform .= '</td>';
			$displayform .= '</tr>';
	    	$displayform .= '<tr><td align=left><img src="'.base_url().'images/upload.png" alt=upload /></td>';
			
			$displayform .= '<td align=left><input type="file" name="userfile" size="20" class="required" accept="xls" />';
			$displayform .= '</td></tr>';
			$displayform .='<tr><td colspan=2 align=center><input class="submit" type="submit" value="Save" />';
			$displayform .='<input type="reset" value="Cancel" /></td>';
			$displayform .= '</tr></table>';
			
			$displayform .= '</fieldset>';
			$displayform .= '</form>';
			
			
			$displayform .= '</div>';
			$data = array('formdisplay'=>$displayform);
			$this->template->add_js('js/jquery-latest.js');	
			$this->template->add_js('js/jquery.validate.js');
			$this->template->add_js('js/jquery.ui.progressbar.js');
			$this->template->add_js('$(document).ready(function(){
		 		   $("#add_upload").validate();
		  			});
			','embed');
			
	
				$this->template->write_view('header','header', $data, True);
				$this->template->write_view('content', 'other_general');
				$this->template->render();
			
		 }
		 else
		 {
		    echo "Forbidden to access!!";
		 }
	}

	function save_bulk_cities()
	{
		$dir = './district_uploads/';


		$config['upload_path'] = $dir;
		$config['allowed_types'] = 'xls';
		$config['max_size']	= '2097152';
		$config['max_width']  = '1024';
		$config['max_height']  = '768';
		$this->load->library('upload',$config);
				
		if (!$this->upload->do_upload()) 
				{
					$error = array('error' => $this->upload->display_errors());
					print_r($error);
				}    
				else
				{	
					$filename = array('upload_data' => $this->upload->data());
				
					$this->load->model('cities_model');
					$filepath = $filename['upload_data']['file_name'];
					
					$this->cities_model->insert_cities($filepath);
					redirect('cities/list_cities/0');
				//	redirect(base_url().'cities/add_cities_in_bulk');					
				}
	}
	//adding new state using ajax...
	function ajax_addnew_cities($new_city = '',$state =0)
  {
    $city_name = str_ireplace("_", " ",$new_city);
    
    $check=$this->cities_model->insert_city($state,$city_name);
    
    if($check == 0)
    {
      echo "<p style='color:red;'> The city name you're trying insert is already exist!!! </p>";
    }
    else
    {
      echo "<p style='color:green;'>Successfully inserted</p>";
    }
  }
  
  	
	function display_cities($id=0)
	{
		 $user_ses = $this->session->userdata('userlogindetails');
 
    if($user_ses['user_id'] && $user_ses['user_group']==1)
    {
		  $this->load->helper('flexigrid');
            
      $displayform ='';
      $state = $this->cities_model->get_statename($id);
      
      $state_name = $state->result_array();
         
      $displayform .= '<table id="flex1" style="display:none" border=0 align=left ></table>';
      $displayform .= '<br/>';
    
      $displayform .='<div><script language="javascript" src="'.base_url().'js/flexigride/flexigrid.pack.js" ></script></div>';
        
      $colModel['city_id'] = array('Sl No',60,TRUE,'center',0);
      $colModel['city_name'] = array('City Name',160,TRUE,'left',2);
    
    $gridParams = array(
      'width' => '800',
      'height' => 400,
      'rp' => 15,
      'rpOptions' => '[10,20,30,40]',
      'pagestat' => 'Displaying:{from} to {to} of {total} items.',
      'blockOpacity' => 0.5,
      'title' => 'List of Cities in '.$state_name[0]['state_name'].'',
      'showTableToggleBtn' => true
    );
    
    $grid_js = build_grid_js('flex1',site_url("/ajax/city_list/".$id),$colModel,'city_id','asc',$gridParams);
    
    $data['js_grid'] = $grid_js;
    
    echo $displayform;
    echo $grid_js;
    
    }
    else
    {
      echo "Forbidden to access!!";
    }
    
  }
		
	/*
	
  
  
  
// to insert new city....	
	function add_new()
	{
		$city_name = array('name'=>'city_name','id'=>'city_name',
				'type'=>'text','class'=>'required');
		$this->load->helper('form');
		$this->load->library('form_validation');
		$displayform ='';
		$displayform .='<div id=dashboard ><span>Manage City</span> <a href='.base_url().'/idea_home/admin_dashboard ><img align=right src="'.base_url().'images/home.png" alt="home" /></a><img align=right src="'.base_url().'images/back.png" alt="back" id=back ONCLICK="history.go(-1)" /></div>';
		
		$displayform .='<fieldset><legend>Add New City</legend>';
		$attr = array('id'=>'new_city');
		
		$displayform .= form_open('cities/add_new',$attr);
		$displayform .= '<table >';
		$displayform .= '<tr><td align=left> State Name</td>';
		$displayform .= '<td><select name=state class=required>';
		$displayform .= '<option value="">-Please Select State-</option>';
		$this->load->model('states_model');
		$states = $this->states_model->disp_states();
		foreach($states->result_array() as $row)
		{
			$displayform .= '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
		}
		$displayform .= '</select></td></tr>';
		$displayform .= '<tr><td align=left> City Name:</td>';
		$displayform .= '<td>'.form_input($city_name).'</td>';
		$displayform .= '</tr>';
		$displayform .= '<tr><td align=center colspan=2>'.form_submit('Submit','Save New City').'</td>';
		$displayform .= '</tr>';
		$displayform .= '</table></fieldset>';
		$displayform .=form_close();
		$this->form_validation->set_rules('state', 'state Name', 'trim|required|xss_clean');
		$this->form_validation->set_rules('city_name', 'City Name', 'trim|required|xss_clean');
		$data = array('formdisplay'=>$displayform );
		//$this->template->add_js('js/jquery-1.3.2.js');
		
		if ($this->form_validation->run() == FALSE)
		{		
			$this->template->add_js('js/jquery-latest.js');	
			$this->template->add_js('js/jquery.validate.js');
			$this->template->add_js('js/validate_xls.js');
			$this->template->add_js('$(document).ready(function(){
	 		   $("#new_city").validate();
	  			});
		','embed');
			$this->template->write_view('header','header', $data, True);
			$this->template->write_view('content', 'general');
			$this->template->render();
		}
		else
		{
			
			$check=$this->cities_model->insert_city();
			
			redirect('cities/list_cities/0');
			
		}
	}
//to display duplicate city name...
	function duplicate_city()
	{
		$displayform ='';
		$displayform .='<div id=dashboard ><span>Manage City</span> <a href='.base_url().'/idea_home/dashboard ><img align=right src="'.base_url().'images/home.png" alt="home" /></a><img align=right src="'.base_url().'images/back.png" alt="back" id=back ONCLICK="history.go(-1)" /></div>';
		$displayform .= "This place already exist,please go back and try for another name!!";
	  $data = array('formdisplay'=>$displayform );
		$this->template->write_view('header','header', $data, True);
			$this->template->write_view('content', 'other_general');
			$this->template->render();
	}
	
   * 
   */
//to edit city name...
	function city_edit($id=0)
	{
	  $user_ses = $this->session->userdata('userlogindetails');
 
    if($user_ses['user_id'] && $user_ses['user_group']==1)
    {
      
		$this->load->helper('form');
		$this->load->library('form_validation');
		
		
		//$state = $name[0];
		
			
			$city_name = $this->cities_model->city_edit($id);
			$name = $city_name->result_array();
			$city_name = array('name'=>'city_name','value'=>$name[0]['city_name'],'type'=>'text','class'=>'required');//its already posted so it will not set again here after validati
			
		
		//$this->form_validation->set_rules('state_name', 'State Name', 'trim|required|xss_clean');
		$displayform ='';
		$displayform .='<div id=dashboard ><span>Manage City</span> <a href='.base_url().'/idea_home/admin_dashboard ><img align=right src="'.base_url().'images/home.png" alt="home" /></a><img align=right src="'.base_url().'images/back.png" alt="back" id=back ONCLICK="history.go(-1)" /></div>';
    $displayform .= '<span style="float:left;">Welcome '.$user_ses['user_name'].'</span><div id=logout>&nbsp;<a href="'.base_url().'idea_home/logout">Logout</a></div>';
    $displayform .= '<br/>'; 
		$displayform .='<fieldset style="width:50%;"><legend>Edit City Name</legend>';
		$attr = array('id'=>'edit_city');
		$displayform .= form_open('cities/save_edit',$attr);
		$displayform .= '<input type=hidden name=id value='.$id.' />';
		$displayform .= '<table class="tablestyle">';
		$displayform .= '<tr><td align=left> City Name:</td>';
		$displayform .= '<td>'.form_input($city_name).'</td>';
		$displayform .= '</tr>';
		
		$displayform .= '<tr><td align=center colspan=2>'.form_submit('submit','Update City').'</td>';
		$displayform .= '</tr>';
		$displayform .= '</table></fieldset>';
		$displayform .=form_close();
					
			$data = array('formdisplay'=>$displayform );
			$this->template->add_js('js/jquery-latest.js');	
			$this->template->add_js('js/jquery.validate.js');
			
			$this->template->add_js('$(document).ready(function(){
	 		   $("#edit_city").validate();
	  			});
		','embed');
			$this->template->write_view('header','header', $data, True);
			$this->template->write_view('content', 'general');
			$this->template->render();
			}
      else
        {
          echo "Forbidden to Access!!";
        }
		}

		//TO SAVE EDITED INFORMATION.........
		function save_edit()
		{
		//print_r($_POST);
		$user_ses = $this->session->userdata('userlogindetails');
 
    if($user_ses['user_id'] && $user_ses['user_group']==1)
    {
			$this->cities_model->save_edit();
			redirect('cities/list_cities/0');
    }
    else
    {
      echo "Forbidden to access";
    }
			
		}
	}
	

